// pages/order/order.js
const request = require("../../utils/request.js");

Page({
  data: {
    orderList: [],        // 订单列表
    statusList: [         // 订单状态筛选（全部、待支付、待收货、已完成）
      { id: 0, name: "全部" },
      { id: 1, name: "待支付" },
      { id: 2, name: "待收货" },
      { id: 3, name: "已完成" }
    ],
    currentStatus: 0,     // 当前选中状态
    pageNum: 1,
    pageSize: 10,
    total: 0,
    isLoading: false
  },

  // 加载订单列表（按状态筛选）
  async getOrderList() {
    if (this.data.isLoading) return;
    if (this.data.pageNum > Math.ceil(this.data.total / this.data.pageSize)) return;

    this.setData({ isLoading: true });
    try {
      const params = {
        status: this.data.currentStatus, // 订单状态（后端定义：0=全部，1=待支付...）
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      };
      const res = await request.get("/api/order/list", params);
      this.setData({
        orderList: this.data.pageNum === 1 ? res.list : [...this.data.orderList, ...res.list],
        total: res.total,
        pageNum: this.data.pageNum + 1,
        isLoading: false
      });
      wx.stopPullDownRefresh();
    } catch (err) {
      console.error("获取订单失败：", err);
      this.setData({ isLoading: false });
    }
  },

  // 切换订单状态筛选
  switchStatus(e) {
    const status = e.currentTarget.dataset.status;
    if (status === this.data.currentStatus) return;
    this.setData({ currentStatus: status, pageNum: 1, orderList: [] });
    this.getOrderList();
  },

  // 确认收货（调用后端接口）
  async confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.orderid;
    // 弹窗确认
    wx.showModal({
      title: "确认收货",
      content: "是否确认已收到商品？",
      success: async (res) => {
        if (res.confirm) {
          try {
            await request.post("/api/order/confirmReceipt", { orderId });
            wx.showToast({ title: "确认收货成功" });
            // 重新加载订单列表
            this.setData({ pageNum: 1, orderList: [] });
            this.getOrderList();
          } catch (err) {
            console.error("确认收货失败：", err);
          }
        }
      }
    });
  }
});